var setter;
layui.use(['setter'], function () {
    setter = layui.setter;
});

layui.define(['laydate', 'upload', 'layedit', 'tree','publicMethods'], function (exports) {
    var $ = layui.$,
        form = layui.form,
        table = layui.table,
        laydate = layui.laydate,
        upload = layui.upload,
        layedit = layui.layedit,
        tree = layui.tree,
        publicMethods = layui.publicMethods,

        colorpicker = layui.colorpicker,
        element = layui.element,
        layer = layui.layer,
        slider = layui.slider,
        formName = '.form-props-info-scroll',
        temPropOpt = 'temPropOpt',
        temProps = 'temProps',
        propSlideOnly = '.propSlideOnly',
        selectStamp = '.selectStamp',
        optName = 'optName',
        defPropName = 'defPropName',
        colorInit = function (name, _color, callback) {
            colorpicker.render({
                elem: name.find('.temColorVal'),
                color: _color,
                done: function (color) {
                    name.find('.temColorInput').val(color);
                    typeof callback == "function" ? callback(color) : null;
                }
            });
        },
        propsHandle = function (obj) {
            form.render();
            element.init();
            var formData = {},
                tag = $(selectStamp + ' ');
            if (obj) {
                formData = obj;
            }

            // 滑动条集合---------------------------
            var sliderObj = $('.' + temProps + ' ' + propSlideOnly);
            if (sliderObj.length > 0) {
                var textDisplay = 'textDisplay',
                    textDisplayName = $('[lay-filter=' + textDisplay + ']').attr('name'),
                    textTitleSite = 'textTitleSite',
                    textTitleSiteName = $('[lay-filter=' + textTitleSite + ']').attr('name'),
                    sliderObjLabel = tag.find('.' + sliderObj.attr('optLeft')),
                    sliderObjInput = tag.find('.' + sliderObj.attr('optRight')),
                    isType = (sliderObjLabel.css('float') === 'left'),
                    sliderInputW = parseInt(((parseInt(sliderObjInput.css('width'), 10) / parseInt(sliderObjInput.parent().css('width'), 10)) * 100), 10),
                    sliderLabelW = parseInt(((parseInt(sliderObjLabel.css('width'), 10) / parseInt(sliderObjLabel.parent().css('width'), 10)) * 100), 10);

                formData[textTitleSiteName] = sliderObjLabel.css('float');
                formData[textDisplayName] = sliderObjLabel.css('display');

                // 滑动
                slider.render({
                    elem: propSlideOnly,
                    value: isType ? [sliderLabelW, (sliderInputW + sliderLabelW)] : sliderInputW,
                    range: isType,
                    max: 100,
                    min: isType ? 10 : 0,
                    change: function (e) {
                        timers(function () {
                            if (isType) {
                                var labelW = (e[0] >= 99 ? 98 : e[0]),
                                    inputW = ((e[1] - e[0]) <= 2 ? 2 : (e[1] - e[0]));
                                sliderObjInput.css('width', inputW + '%');
                                sliderObjLabel.css('width', labelW + '%');
                            } else {
                                sliderObjInput.css('width', e + '%');
                            }
                        });
                    }
                });


                form.on('radio(' + textDisplay + ')', function (data) {
                    var isLabel = $('[name=' + textTitleSiteName + ']')[0].checked;
                    if (isLabel) {
                        sliderObjLabel.css('display', data.value);
                    } else {
                        sliderObjLabel.css('display', 'block');
                        sliderObjLabel.css('visibility', data.value === 'none' ? 'hidden' : 'inherit');
                    }
                });

                form.on('radio(' + textTitleSite + ')', function (data) {
                    var isBool = (data.value === 'left'), isLabel = $('[name=' + textDisplayName + ']')[0].checked;
                    sliderObjInput.css('width', isBool ? '90%' : '100%');
                    sliderObjLabel.css('width', isBool ? '10%' : '100%').css('float', data.value);
                    if (!isLabel) {
                        sliderObjLabel.css('display', isBool ? 'block' : 'none');
                        sliderObjLabel.css('visibility', isBool ? 'hidden' : 'inherit');
                    }

                    slider.render({
                        elem: propSlideOnly,
                        value: 100,
                        range: isBool,
                        max: 100,
                        min: isBool ? 10 : 0,
                        change: function (e) {
                            timers(function () {
                                if (isBool) {
                                    var labelW = (e[0] >= 99 ? 98 : e[0]),
                                        inputW = ((e[1] - e[0]) <= 2 ? 2 : (e[1] - e[0]));
                                    sliderObjInput.css('width', inputW + '%');
                                    sliderObjLabel.css('width', labelW + '%');
                                } else {
                                    sliderObjInput.css('width', e + '%');
                                }
                            });

                        }
                    });

                });

            }


            // ------------------------------------------


            // input value 类型

            $(formName).find('.temInput').each(function () {
                var _name = $(this).attr(optName);
                formData[$(this).attr('name')] = $(selectStamp + (!!_name ? ' .' + _name : '')).css($(this).attr(temPropOpt));
                $(this).keydown(function () {
                    var _this = $(this),
                        _thisName = _this.attr(optName);
                    timers(function () {
                        $(selectStamp + (!!_thisName ? ' .' + _thisName : '')).css(_this.attr(temPropOpt), _this.val());
                    });
                });


            });

            $(formName).find('.temInputAttr').each(function () {
                var _name = $(this).attr(optName);
                formData[$(this).attr('name')] = $(selectStamp + (!!_name ? ' .' + _name : '')).attr($(this).attr(temPropOpt));
                $(this).keydown(function () {
                    var _this = $(this),
                        _thisName = _this.attr(optName);
                    timers(function () {
                        $(selectStamp + (!!_thisName ? ' .' + _thisName : '')).attr(_this.attr(temPropOpt), _this.val());
                    });
                });


            });


            // select
            $(formName).find('.temSelect').each(function () {
                var _name = $(this).attr(optName);
                formData[$(this).find('select').attr('name')] = $(selectStamp + (!!_name ? ' .' + _name : '')).css($(this).attr(temPropOpt));
            });
            form.on('select(temSelect)', function (data) {
                var _name = $(this).attr(optName),
                    _opt = $(this).parents('.temSelect').attr(temPropOpt);
                $(selectStamp + (!!_name ? ' .' + _name : '')).css(_opt, data.value);
            });

            // radio
            $(formName).find('.temRadio').each(function () {
                var _name = $(this).attr(optName);
                formData[$(this).find('input').attr('name')] = $(selectStamp + (!!_name ? ' .' + _name : '')).css($(this).attr(temPropOpt));
            });

            form.on('radio(temRadio)', function (data) {
                var _name = $(this).parents('.temRadio').attr(optName),
                    _opt = $(this).parents('.temRadio').attr(temPropOpt);
                $(selectStamp + (!!_name ? ' .' + _name : '')).css(_opt, data.value);
            });

            $(formName).find('.temRadioAttr').each(function () {
                var _name = $(this).attr(optName);
                formData[$(this).find('input').attr('name')] = $(selectStamp + (!!_name ? ' .' + _name : '')).attr($(this).attr(temPropOpt));
            });

            form.on('radio(temRadioAttr)', function (data) {
                var _name = $(this).parents('.temRadioAttr').attr(optName),
                    _opt = $(this).parents('.temRadioAttr').attr(temPropOpt);
                $(selectStamp + (!!_name ? ' .' + _name : '')).attr(_opt, data.value);
            });


            // text 赋值类型
            $(formName).find('.temText').each(function () {
                var _name = $(this).attr(optName);
                formData[$(this).attr('name')] = $.trim($(selectStamp + (!!_name ? ' .' + _name : '')).text());

                $(this).keydown(function () {
                    var _this = $(this),
                        _thisName = _this.attr(optName);
                    timers(function () {
                        $(selectStamp + (!!_thisName ? ' .' + _thisName : '')).text(_this.val());
                        form.render();
                    });
                });

            });


            // color

            $(formName).find('.temColor').each(function () {
                var _this = $(this),
                    _name = $(this).attr(optName),
                    _color = $(selectStamp + (!!_name ? ' .' + _name : '')).css(_this.attr(temPropOpt)).colorHex(),
                    _input = _this.find('.temColorInput');
                _input.val(_color);
                colorInit(_this, _color, function (color) {
                    $(selectStamp + (!!_name ? ' .' + _name : '')).css(_this.attr(temPropOpt), color);
                });
                _input.keydown(function () {
                    var that = $(this);
                    timers(function () {
                        colorInit(_this, that.val(), function (color) {
                            $(selectStamp + (!!_name ? ' .' + _name : '')).css(_this.attr(temPropOpt), color);
                        });
                        $(selectStamp + (!!_name ? ' .' + _name : '')).css(_this.attr(temPropOpt), that.val());
                    });
                });

            });

            form.on('select(eventPropsKey)', function (data) {
                var _name = $(data.elem).parents('.eventProps').attr(optName),
                    _option = $(data.elem).find('option'),
                    selectObj = $(selectStamp + (!!_name ? ' .' + _name : '')),
                    _evenVal = $(data.elem).parent().find('.eventPropsVal').val(),
                    selectAttr = [];
                selectObj.each(function () {
                    $.each(this.attributes, function () {
                        if (this.specified) {
                            var nameObj = this.name;
                            _option.each(function (i, item) {
                                var _val = $(item).val();
                                if (_val === nameObj) {
                                    selectAttr.push(_val);
                                }
                            })
                        }
                    });
                });
                selectObj.removeAttr(selectAttr.join(' '));
                if(data.value != ''){
                    selectObj.attr(data.value, _evenVal);
                }
            });

            var _stampNameEven = $('.eventProps').attr(optName)

            $(selectStamp + (!!_stampNameEven ? ' .' + _stampNameEven : '')).each(function () {
                var _this = this;
                $.each(this.attributes, function () {
                    if (this.specified) {
                        var _nameVal = this.name;
                        $('select[name=eventPropsKey]').find('option').each(function (i, item) {
                            var _val = $(item).val();
                            if (_val === _nameVal) {
                                formData['eventPropsKey'] = _val;
                                formData['eventPropsVal'] = $(_this).attr(_val);
                            }
                        })
                    }
                });
            });

            form.val(temProps, formData);


            $('.addProperty').click(function () {
                $('.addPropsHandle').append('<div class="form-props-input"><input type="text" autocomplete="off" class="layui-input propKey"><input type="text" autocomplete="off" class="layui-input propVal"><i class="layui-icon layui-icon-delete itemDel"></i></div>');
            });

            $('.addPropsHandle').on('click', '.itemDel', function () {
                var _name = $('.addPropsHandle').attr(optName),
                    // selectObj = $(selectStamp + (!!_name?' .'+_name:'') ),
                    key = $(this).parent().find('.propKey').val();
                if (/^[a-z][a-z0-9_-]*$/.test(key)) {
                    $(selectStamp + (!!_name ? ' .' + _name : '')).removeAttr(key);
                }
                $(this).parent().remove();
            });


            var _stampName = $('.addPropsHandle').attr(optName),
                defPropList = !!$('.addPropsHandle').attr(defPropName) ? $('.addPropsHandle').attr(defPropName).split(',') : [];
            $('.addPropsHandle').html('');
            $(selectStamp + (!!_stampName ? ' .' + _stampName : '')).each(function () {
                $.each(this.attributes, function () {
                    if (this.specified) {
                        var isHide = defPropList.indexOf(this.name) > -1;
                        $('.addPropsHandle').append('<div class="form-props-input"><input type="text" autocomplete="off" ' + (isHide ? ('disabled="disabled"') : '') + ' value="' + this.name + '" class="layui-input propKey"><input type="text" ' + (isHide ? ('disabled="disabled"') : '') + ' autocomplete="off" value="' + this.value + '" class="layui-input propVal">' + (isHide ? '' : '<i class="layui-icon layui-icon-delete itemDel"></i>') + '</div>');
                    }
                });
            });

            $('.addPropsHandle').on('keydown', '.form-props-input input', function () {
                timers(function () {
                    var _name = $('.addPropsHandle').attr(optName),
                        selectObj = $(selectStamp + (!!_name ? ' .' + _name : '')),
                        selectAttr = [];
                    selectObj.each(function () {
                        $.each(this.attributes, function () {
                            if (this.specified && defPropList.indexOf(this.name) < 0) {
                                selectAttr.push(this.name);
                            }
                        });
                    });

                    selectObj.removeAttr(selectAttr.join(' '));

                    $('.addPropsHandle .form-props-input').each(function (i, item) {
                        var key = $(item).find('.propKey').val();
                        if (!!key) {
                            if (/^[a-z][a-z0-9_-]*$/.test(key)) {
                                var val = $(item).find('.propVal').val();
                                $(selectStamp + (!!_name ? ' .' + _name : '')).attr(key, val);
                            } else {
                                timers(function () {
                                    layer.msg('key请按照属性规则，以字母开头的英文内容，可出现下划线及减号');
                                });
                            }
                        }
                    });
                });
            });


            $('.eventProps').on('keydown', '.form-props-input .eventPropsVal', function () {
                var _this = this;
                timers(function () {
                    var _name = $('.eventProps').attr(optName),
                        _key = $(_this).parent().find('select').val(),
                        selectObj = $(selectStamp + (!!_name ? ' .' + _name : ''));
                    if (_key) {
                        selectObj.attr(_key, $(_this).val());
                    }
                });
            });


            form.on('select(temSelectCont)', function (data) {
                $(data.elem).change();
            });


            $('.temCustomDialog').click(function () {
                $.ajax({
                    url: serverPath.qbdmsPath + setter.formLinkPath + 'table/getByMainTableId',
                    type: 'GET',
                    contentType: 'application/json',
                    dataType: 'json',
                    async: false,
                    data: {
                        tableId: obj.tableid
                    },
                    success: function (result) {
                        var tableMeans = result.data.tableMeans,
                        fieldList = result.data.mainTable.fieldList;

                        function strFieldList(){
                            var strLi = '';
                            for (var i = 0; i < fieldList.length; i++) {
                                strLi += '<option value="' + fieldList[i].fieldName + '">' + fieldList[i].fieldDesc + '</option>'
                            }

                            return strLi;
                        }
                        //按钮-自定义对话框设置（对象）
                        var dialogInstall = {};
                        dialogInstall.powerInherit = fieldList[0].fieldName;
                        dialogInstall.tableName = result.data.mainTable.tableName;
                        layer.open({
                            type: '1',
                            content: '<div class="layui-tab layui-tab-card"  style="width: 568px;">' +
                                '<ul class="layui-tab-title">' +
                                '<li class="layui-this" tableid="'+tableMeans[0].tableId+'">' + tableMeans[0].name + '</li>' +
                                function () {
                                   var  strLi = '';
                                    for (var i = 1; i < tableMeans.length; i++) {
                                        strLi += '<li style="display: none" tableid="' + tableMeans[i].tableId + '">' + tableMeans[i].name + '</li>'
                                    }
                                    return strLi;
                                }() +
                                '</ul>' +
                                '<div class="layui-tab-content layui-form" style="height: 500px;">' +
                                '<div class="layui-tab-item layui-show">' +
                                '<div class="winDialogSetting">' +
                                '<div class="winDialogTitle"><span>对话框设置</span></div>' +
                                '<div class="layui-form-item">' +
                                '<label class="layui-form-label">权限继承</label>' +
                                '<span class="winDialogTag">弹出框显示权限将继承该字段的权限</span>' +
                                '<div class="layui-input-block" style="width: 200px;">' +
                                '<select name="powerInherit" lay-filter="powerInherit" value="'+fieldList[0].fieldName+'">' +
                                strFieldList() +
                                '</select>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layui-form-item">' +
                                '<label class="layui-form-label">选择对话框</label>' +
                                '<div class="layui-input-block" style="width: 200px;">' +
                                '<select name="selectTalk" lay-filter="selectTalk">' +
                                '<option value=""></option>' +
                                function () {
                                    var strLi = '',
                                        allDialogs = result.data.allDialogs;
                                    for (var i = 0; i < allDialogs.length; i++) {
                                        strLi += '<option value="dialog_' + allDialogs[i].alias + '">' + allDialogs[i].name + '</option>'
                                    }
                                    var allCombinations = result.data.allCombinations;
                                    for (var j = 0; j < allCombinations.length; j++) {
                                        strLi += '<option value="combination_' + allCombinations[j].alias + '">' + allCombinations[j].name + '</option>'
                                    }
                                    return strLi;
                                }() +
                                '</select>' +
                                '</div>' +
                                '</div>' +
                                '<div class="layui-form-item">' +
                                '<label class="layui-form-label">查询条件</label>' +
                                '<div class="layui-input-block selectFactor" >' +
                                '</div>' +
                                '</div>' +
                                '<div class="winDialogTitle"><span>回填值设置</span></div>' +
                                '<ul id="treeDom" class="ztree"></ul>' +
                                '<div class="domBtnDiv">' +
                                '<div class="categoryDiv">' +
                                '</div>' +
                                '</div>' +
                                '</div>' +
                                // '<div class="layui-tab-item"></div>' +
                                '</div>' +
                                '</div>',
                            title: '自定义对话框',
                            area: '570px',
                            closeBtn:0,
                            btn: ['保存', '取消'],
                            btnAlign: 'c',
                            skin: 'form-custom-dialog',
                            success: function () {
                                $(window).resize();
                                form.render();

                                var MoveTest = {
                                    curTarget: null,
                                    curTmpTarget: null,
                                    noSel: function() {
                                        try {
                                            window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
                                        } catch(e){}
                                    },
                                    dragTree2Dom: function(treeId, treeNodes) {
                                        return !treeNodes[0].isParent;
                                    },
                                    innerTree: function(treeId, treeNodes, targetNode) {
                                        return !!targetNode && (targetNode.isParent || targetNode.tId == treeNodes[0].parentTId);
                                    },
                                    dragMove: function(e, treeId, treeNodes) {
                                        $('.domBtnDiv .active').removeClass('active');
                                    },
                                    dropTree2Dom: function(e, treeId, treeNodes, targetNode, moveType) {
                                        if (moveType == null) {
                                            var zTree = $.fn.zTree.getZTreeObj("treeDom");
                                            zTree.removeNode(treeNodes[0]);
                                            var newDom = $("span[domId=" + treeNodes[0].fieldName + "]");
                                            if (newDom.length > 0) {
                                                newDom.removeClass("domBtn_Disabled");
                                                newDom.addClass("domBtn");
                                            }
                                            MoveTest.updateType();
                                        }

                                    },
                                    dom2Tree: function(e, treeId, treeNode) {
                                        var target = MoveTest.curTarget, tmpTarget = MoveTest.curTmpTarget;
                                        if (!target) return;
                                        var zTree = $.fn.zTree.getZTreeObj("treeDom");
                                        if (tmpTarget) tmpTarget.remove();
                                        if (!!treeNode) {
                                            var nodes = zTree.addNodes(treeNode, {fieldName:target.attr("domId"), comment: target.text()});
                                            console.log(nodes)
                                            if(!!nodes){
                                                zTree.selectNode(nodes[0]);
                                            }else{
                                                target.removeClass("domBtn_Disabled");
                                                target.addClass("domBtn");
                                            }
                                        } else {
                                            target.removeClass("domBtn_Disabled");
                                            target.addClass("domBtn");
                                        }
                                        MoveTest.updateType();
                                        MoveTest.curTarget = null;
                                        MoveTest.curTmpTarget = null;
                                    },
                                    updateType: function() {
                                        var zTree = $.fn.zTree.getZTreeObj("treeDom"),
                                            nodes = zTree.getNodes();
                                        for (var i=0, l=nodes.length; i<l; i++) {
                                            var num = nodes[i].children ? nodes[i].children.length : 0;
                                            nodes[i].fieldName = nodes[i].fieldName.replace(/ \(.*\)/gi, "") + " (" + num + ")";
                                            zTree.updateNode(nodes[i]);
                                        }
                                    },
                                    bindDom: function() {
                                        $(".domBtnDiv").bind("mousedown", MoveTest.bindMouseDown);
                                    },
                                    bindMouseDown: function(e) {
                                        var target = e.target;
                                        if (target!=null && target.className=="domBtn") {
                                            var doc = $(document), target = $(target),
                                                docScrollTop = doc.scrollTop(),
                                                docScrollLeft = doc.scrollLeft(),
                                                curDom = $("<span class='dom_tmp domBtn'>" + target.text() + "</span>");
                                            target.addClass("domBtn_Disabled");
                                            target.removeClass("domBtn");
                                            curDom.appendTo("body");
                                            curDom.css({
                                                "top": (e.clientY + docScrollTop + 3) + "px",
                                                "left": (e.clientX + docScrollLeft + 3) + "px"
                                            });
                                            MoveTest.curTarget = target;
                                            MoveTest.curTmpTarget = curDom;
                                            doc.bind("mousemove", MoveTest.bindMouseMove);
                                            doc.bind("mouseup", MoveTest.bindMouseUp);
                                            doc.bind("selectstart", MoveTest.bindSelect);
                                        }
                                        if(e.preventDefault) {
                                            e.preventDefault();
                                        }
                                    },
                                    bindMouseMove: function(e) {
                                        MoveTest.noSel();
                                        var doc = $(document),
                                            docScrollTop = doc.scrollTop(),
                                            docScrollLeft = doc.scrollLeft(),
                                            tmpTarget = MoveTest.curTmpTarget;
                                        if (tmpTarget) {
                                            tmpTarget.css({
                                                "top": (e.clientY + docScrollTop + 3) + "px",
                                                "left": (e.clientX + docScrollLeft + 3) + "px"
                                            });
                                        }
                                        return false;
                                    },
                                    bindMouseUp: function(e) {
                                        var doc = $(document);
                                        doc.unbind("mousemove", MoveTest.bindMouseMove);
                                        doc.unbind("mouseup", MoveTest.bindMouseUp);
                                        doc.unbind("selectstart", MoveTest.bindSelect);

                                        var target = MoveTest.curTarget, tmpTarget = MoveTest.curTmpTarget;
                                        if (tmpTarget) tmpTarget.remove();

                                        if ($(e.target).parents("#treeDom").length == 0) {
                                            if (target) {
                                                target.removeClass("domBtn_Disabled");
                                                target.addClass("domBtn");
                                            }
                                            MoveTest.curTarget = null;
                                            MoveTest.curTmpTarget = null;
                                        }
                                    },
                                    bindSelect: function() {
                                        return false;
                                    }
                                };




                                var setting;
                                form.on('select(selectTalk)',function (dataSele) {
                                    //将选择的对话框保存到自定义对话框设置（对象）中
                                    dialogInstall.selectDialogAlias = dataSele.value;

                                    if(dataSele.value !== ''){
                                        var allDialog;
                                        //判断选中对话框是否是组合对话框，组合对话框value为combination_开头，普通对话框为dialog_开头
                                        if(dataSele.value[0] === 'c'){
                                            for(var combinationIndex in result.data.allCombinations){
                                                var combinationDialog = result.data.allCombinations[combinationIndex];
                                                if(combinationDialog.alias === dataSele.value.substr(12)){
                                                    allDialog = combinationDialog.listDialog;
                                                    break;
                                                }
                                            }
                                        }else {
                                            for(var dialogIndex in result.data.allDialogs){
                                                var dialog = result.data.allDialogs[dialogIndex];
                                                if(dialog.alias === dataSele.value.substr(7)){
                                                    allDialog = dialog;
                                                    break;
                                                }
                                            }
                                        }
                                        var conditionfie = JSON.parse(allDialog.conditionfield),
                                            fieldList = result.data.mainTable.fieldList,
                                            str = '',liStr = '';
                                        setting = {
                                            edit: {
                                                enable: true,
                                                showRemoveBtn: false,
                                                showRenameBtn: false,
                                                drag: {
                                                    prev: false,
                                                    next: false,
                                                    inner: MoveTest.innerTree
                                                }
                                            },
                                            data: {
                                                keep: {
                                                    parent: true,
                                                    leaf: true
                                                },
                                                simpleData: {
                                                    enable: true
                                                },
                                                key:{
                                                    id:'fieldName',
                                                    name:'comment'
                                                }
                                            },
                                            callback: {
                                                beforeDrag: MoveTest.dragTree2Dom,
                                                onDrop: MoveTest.dropTree2Dom,
                                                onDragMove: MoveTest.dragMove,
                                                onMouseUp: MoveTest.dom2Tree
                                            },
                                            view: {
                                                selectedMulti: false
                                            }
                                        };
                                        $.fn.zTree.init($("#treeDom"), setting, allDialog.returnList);
                                        MoveTest.updateType();
                                        MoveTest.bindDom();

                                        for(var c = 0;c<fieldList.length; c++){
                                            liStr += '<span class="domBtn" domId="'+fieldList[c].fieldName+'">'+fieldList[c].fieldDesc+'</span>'
                                        }

                                        $('.categoryDiv').html(liStr);

                                        //自定义对话框设置（对象）-条件字段数据
                                        dialogInstall.conditionField = [];
                                        for(var k = 0; k < conditionfie.length; k++){
                                            //当字段为动态传入时，才添加为条件字段
                                            str += '<div class="selectFactorLi">' +
                                                '<input type="checkbox" lay-filter="seleCheck" fieid="' + conditionfie[k].field + '" name="seleCheck[' + conditionfie[k].field + ']" lay-skin="primary" title="' + conditionfie[k].comment + '">' +
                                                '<div class="selectFactorState">' +
                                                '<div class="selectFactorSele">' +
                                                '<select name="" id="field_' + conditionfie[k].field + '" lay-filter="" value="' + fieldList[0].fieldName + '">' +
                                                strFieldList() +
                                                '</select>' +
                                                '</div>' +
                                                '<input type="text" name="" id="init_' + conditionfie[k].field + '" autocomplete="off" placeholder="预设值" class="layui-input selectFactorInput">' +
                                                '</div>' +
                                                '</div>';
                                        }

                                        $('.form-custom-dialog .selectFactor').html(str);
                                        form.render();

                                    }
                                });

                                form.on('checkbox(seleCheck)',function (dataCheck) {
                                    var checkFieId = $(dataCheck.elem).attr('fieid');
                                    if(dataCheck.elem.checked){

                                        //自定义对话框设置（对象）-条件字段内容
                                        dialogInstall.conditionField.push({'field':checkFieId,'selectField':null,'initValue':null});

                                        $(dataCheck.elem).siblings('.selectFactorState').show();
                                    }else{
                                        $(dataCheck.elem).siblings('.selectFactorState').hide();

                                        //移除条件字段对应数据
                                        for(var i=0;i<dialogInstall.conditionField.length;i++){
                                            if(dialogInstall.conditionField[i].field === checkFieId){
                                                dialogInstall.conditionField.splice(i,1);
                                                break;
                                            }
                                        }
                                    }
                                });

                                //修改设置对象中的权限继承字段
                                form.on('select(powerInherit)',function (dataSele) {
                                    dialogInstall.powerInherit = dataSele.value;
                                });

                                //自定义对话框设置-数据回填
                                var installJson = $(selectStamp).find('.temButton').attr('dialoginstall');
                                if(installJson != null) {
                                    var installData = $.parseJSON(installJson);
                                    $("select[name='powerInherit']").val(installData.powerInherit);
                                    $("select[name='selectTalk']").siblings('div.layui-form-select').find('dl').find("dd[lay-value='"+installData.selectDialogAlias+"']").click();
                                    for(var i=0;i<installData.conditionField.length;i++){
                                        var conditionCheckBox = $("input[fieid='"+installData.conditionField[i].field+"']").siblings('div.layui-form-checkbox');
                                        conditionCheckBox.click();
                                        $("#field_"+installData.conditionField[i].field).val(installData.conditionField[i].selectField);
                                        $("#init_"+installData.conditionField[i].field).val(installData.conditionField[i].initValue);
                                    }

                                    var treeObj = $.fn.zTree.init($("#treeDom"),setting,installData.zTreeNodes);
                                    treeObj.expandAll(true);
                                    for(var i=0;i<installData.treeSelectField.length;i++){
                                        var isSelectField = $(".categoryDiv").find("span[domid='"+installData.treeSelectField[i]+"']");
                                        isSelectField.addClass("domBtn_Disabled");
                                        isSelectField.removeClass("domBtn");
                                    }
                                    form.render();
                                }


                            },
                            yes: function (index) {
                                // 确定
                                //添加自定义对话框设置条件字段数据
                                for(var i=0;i<dialogInstall.conditionField.length;i++){
                                    var checkFie = dialogInstall.conditionField[i];
                                    checkFie.selectField = $("#field_"+checkFie.field).val();
                                    checkFie.initValue = $("#init_"+checkFie.field).val();
                                }
                                //添加自定义对话框设置-树结构数据
                                var zTree = $.fn.zTree.getZTreeObj("treeDom");
                                var parentNodes = zTree.getNodes();
                                dialogInstall.zTreeNodes = [];
                                dialogInstall.treeSelectField = [];
                                for(var i=0;i<parentNodes.length;i++){
                                    var nodeData = {};
                                    nodeData.comment = parentNodes[i].comment;
                                    nodeData.fieldName = parentNodes[i].fieldName;
                                    nodeData.children = [];
                                    var childNodes = zTree.transformToArray(parentNodes[i]);
                                    for(var j=1;j<childNodes.length;j++){
                                        var childData = {};
                                        childData.comment = childNodes[j].comment;
                                        childData.fieldName = childNodes[j].fieldName;
                                        nodeData.children.push(childData);
                                        //添加自定义对话框设置-树结构选中字段数据
                                        dialogInstall.treeSelectField.push(childNodes[j].fieldName);
                                    }
                                    dialogInstall.zTreeNodes.push(nodeData);
                                }
                                $(selectStamp).find('.temButton').attr('dialoginstall',JSON.stringify(dialogInstall));
                                layer.close(index);
                            },
                            cancel: function () {
                                // 取消
                            }
                        })
                    }
                })

            })


        };

    propsHandle.prototype.initTem = function (defProps) {
        // 数据词典 特殊处理

        $(document).on("click", ".temCont .lexiTree .layui-select-title", function (e) {
            $(".temCont .lexiTree .layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected");
            $(this).parents(".dataLexiPanel").toggleClass("layui-form-selected");
            layui.stope(e);
        }).on("click", "dl i", function (e) {
            layui.stope(e);
        });
        $(document).on("click", function (e) {
            $(".temCont .lexiTree .layui-form-select").removeClass(".temCont layui-form-selected");
        });

        // 上传
        $(document).on('click', '.deleteFile', function () {
            $(this).parent().parent().siblings("input[type=button]").show()
            // $(this).parent().parent().siblings("button").show()
            $(this).parent().remove();
        });
        var highet = $(document).find("body").height();
        $(document).find("div.layui-table-view-body").css("min-height",highet-34);
        window.onresize = function(){
            var highet = $(document).find("body").height();
            $(document).find("div.layui-table-view-body").css("min-height",highet-34);
        }
        setTimeout(function () {
            $(".layui-form-label").each(function (i,v) {
                var str = '';
                str = $(this).text();
                if( (str.indexOf("时间") != -1||str.indexOf("日期") != -1||str.indexOf("周期") != -1||str.indexOf("统计期") != -1||str.indexOf("年度") != -1||str.indexOf("年份") != -1)&&((str.indexOf("归零周期(天)") == -1)) ){
                    $(this).siblings("div.layui-input-block").append('<i class="layui-icon layui-icon-date" style="position: absolute;top: 13px;right: 10px;"></i>')
                }
            })
            $(".qbdms-temTable-td input").each(function (i,v) {
                var str = '';
                str = $(this).attr('lay-reqtext');
                if (str){
                    if( (str.indexOf("时间") != -1||str.indexOf("日期") != -1||str.indexOf("周期") != -1||str.indexOf("统计期") != -1||str.indexOf("年度") != -1)&&((str.indexOf("资金") != -1)==(str.indexOf("经费") != -1)) ){
                        $(this).after('<i class="layui-icon layui-icon-date" style="position: absolute;top: 20px;right: 16px;"></i>')
                        $(this).parent("td").css("position","relative")
                    }
                }
            })
        },500)
        // 选择器 交互逻辑处理
        $(document).on('click', '.selectorLi p i', function () {
            $(this).parent().siblings("ul.selectorTake").toggle()
            $(this).siblings("span").toggle()
            var isSpreads = $(this).hasClass('layui-icon-prev');
            if (isSpreads){
                $(this).parent().parent(".selectorLi").css("width","35px")
                $(this).parent().parent(".selectorLi").siblings(".selectorListTab").css("margin-right","50px")
            }else {
                $(this).parent().parent(".selectorLi").css("width","180px")
                $(this).parent().parent(".selectorLi").siblings(".selectorListTab").css("margin-right","187px")
            }
            layui.table.resize($(this).parent().parent(".selectorLi").siblings(".selectorListTab").children("table").attr("id"));

        });
        // 选择器部分公共全局声明
        var selectorIds = [];
        var selectorNames = [];
        var currentData = [];
        var treeId = '';
        var objSelector = {};
        var itemName='';

        // 选择器公共方法

        // 初始化列表
        function selectorTableInit() {
            var sele = $("[lay-id='selectorListTab']").find(".filter-value");
            var whereNew = {};
            whereNew[objSelector.where.id] = treeId;
            whereNew[objSelector.where.name] = sele.val();


            table.render({
                elem: '#selectorListTab',
                method: 'get',
                url: serverPath.qbdmsPath + setter.sysLinkPath + objSelector.server,
                page: true,
                height: 'full-250',
                where: whereNew,
                defaultToolbar:[],
                toolbar: '#headerManagement',
                cols: [objSelector.cols],
                parseData: function (res) {
                    currentData = res.data;
                    if (selectorIds.length > 0) {
                        for (var i = 0; i < currentData.length; i++) {
                            for (var j = 0; j < selectorIds.length; j++) {
                                if (currentData[i][objSelector.id] === selectorIds[j]) {
                                    currentData[i].LAY_CHECKED = true;
                                }
                            }
                        }
                    }
                }
            });
            form.val('selectorQueryForm', {
                'selectorSearch': sele.val()
            });
        }

        // 初始化选中列表部分
        function selectorListInit() {
            $('.selectorTake').html('');
            for (var i = 0; i < selectorIds.length; i++) {
                $('.selectorTake').append('<li><p>' + selectorNames[i] + '</p><i trId=' + selectorIds[i] + ' class="layui-icon layui-icon-delete selectorTakeDel"></i></li>');
            }
        }

        // 初始化机构树
        function selectorTabQuery(listAll) {
            if (listAll == "1") {
                $.ajax({
                    url: serverPath.qbdmsPath + setter.sysLinkPath + 'sysOrg/listAll',
                    type: "GET",
                    contentType: 'application/json',
                    dataType: 'json',
                    async: false,
                    success: function (result) {
                        var zNodes = result.data;
                        for(var i = 0; i < zNodes.length;i++){
                            zNodes[i].iconSkin ="diy"
                            // zNodes[i].iconOpen ="${ctx}/qbdmsStatic/images/no.png"
                            // zNodes[i].iconClose ="${ctx}/qbdmsStatic/images/word.png"
                        }
                        if (zNodes.length > 0) {
                            var setting = {
                                    view: {
                                        showLine: true,
                                        nameIsHTML: true
                                    },
                                    data: {
                                        simpleData: {
                                            enable: true,
                                            idKey:"orgId",
                                            pIdKey:"orgSupId"
                                        }
                                    },
                                    callback: {
                                        onClick: function (event, treeName, treeNode, clickFlag) {
                                            treeId = treeNode.orgId;
                                            selectorTableInit();
                                        }
                                    }
                                },
                                treeObj = $.fn.zTree.init($('#orgTree'), setting, zNodes),
                                node = treeObj.getNodeByParam("orgId", treeId);
                            treeObj.selectNode(node);

                            selectorTableInit();
                            selectorListInit();


                            table.on('checkbox(selectorListTab)', function (obj) {
                                if (obj.type === 'one') {
                                    if (obj.checked) {
                                        selectorIds.push(obj.data[objSelector.id]);
                                        selectorNames.push(obj.data[objSelector.name]);
                                    } else {
                                        var ind = selectorIds.indexOf(obj.data[objSelector.id]);
                                        selectorIds.splice(ind, 1);
                                        selectorNames.splice(ind, 1);
                                    }
                                } else {
                                    for (var k = 0; k < currentData.length; k++) {
                                        var indA = selectorIds.indexOf(currentData[k][objSelector.id]);
                                        if (obj.checked) {
                                            if (indA < 0) {
                                                selectorIds.push(currentData[k][objSelector.id]);
                                                selectorNames.push(currentData[k][objSelector.name]);
                                            }
                                        } else {
                                            if (indA > -1) {
                                                selectorIds.splice(indA, 1);
                                                selectorNames.splice(indA, 1);
                                            }
                                        }
                                    }

                                }

                                selectorListInit();
                            });

                            table.on('radio(selectorListTab)', function (obj) {
                                selectorIds = [obj.data[objSelector.id]];
                                selectorNames = [obj.data[objSelector.name]];
                                selectorListInit();
                            });

                            table.on('toolbar(selectorListTab)', function (obj) {
                                switch (obj.event) {
                                    case 'query':
                                        selectorTableInit();

                                        break;
                                }
                            });


                        }
                    }
                });
            } else {
                $.ajax({
                    url: serverPath.qbdmsPath + setter.sysLinkPath + 'sysOrg/list',
                    type: "GET",
                    contentType: 'application/json',
                    dataType: 'json',
                    async: false,
                    success: function (result) {
                        var zNodes = result.data;
                        for(var i = 0; i < zNodes.length;i++){
                            zNodes[i].iconSkin ="diy"
                            // zNodes[i].iconOpen ="${ctx}/qbdmsStatic/images/no.png"
                            // zNodes[i].iconClose ="${ctx}/qbdmsStatic/images/word.png"
                        }
                        if (zNodes.length > 0) {
                            var setting = {
                                    view: {
                                        showLine: true,
                                        nameIsHTML: true
                                    },
                                    data: {
                                        simpleData: {
                                            enable: true,
                                            idKey:"orgId",
                                            pIdKey:"orgSupId"
                                        }
                                    },
                                    callback: {
                                        onClick: function (event, treeName, treeNode, clickFlag) {
                                            treeId = treeNode.orgId;
                                            selectorTableInit();
                                        }
                                    }
                                },
                                treeObj = $.fn.zTree.init($('#orgTree'), setting, zNodes),
                                node = treeObj.getNodeByParam("orgId", treeId);
                            treeObj.selectNode(node);

                            selectorTableInit();
                            selectorListInit();


                            table.on('checkbox(selectorListTab)', function (obj) {
                                if (obj.type === 'one') {
                                    if (obj.checked) {
                                        selectorIds.push(obj.data[objSelector.id]);
                                        selectorNames.push(obj.data[objSelector.name]);
                                    } else {
                                        var ind = selectorIds.indexOf(obj.data[objSelector.id]);
                                        selectorIds.splice(ind, 1);
                                        selectorNames.splice(ind, 1);
                                    }
                                } else {
                                    for (var k = 0; k < currentData.length; k++) {
                                        var indA = selectorIds.indexOf(currentData[k][objSelector.id]);
                                        if (obj.checked) {
                                            if (indA < 0) {
                                                selectorIds.push(currentData[k][objSelector.id]);
                                                selectorNames.push(currentData[k][objSelector.name]);
                                            }
                                        } else {
                                            if (indA > -1) {
                                                selectorIds.splice(indA, 1);
                                                selectorNames.splice(indA, 1);
                                            }
                                        }
                                    }

                                }

                                selectorListInit();
                            });

                            table.on('radio(selectorListTab)', function (obj) {
                                selectorIds = [obj.data[objSelector.id]];
                                selectorNames = [obj.data[objSelector.name]];
                                selectorListInit();
                            });

                            table.on('toolbar(selectorListTab)', function (obj) {
                                switch (obj.event) {
                                    case 'query':
                                        selectorTableInit();

                                        break;
                                }
                            });


                        }
                    }
                });
            }



            // $.ajax({
            //     url: serverPath.systemPath + setter.sysLinkPath + "sysOrg/list",
            //     type: "get",
            //     contentType: 'application/json',
            //     dataType: 'json',
            //     success: function (data) {
            //         if (commons._filterRecord(data)) {
            //             var zNodes = data.data;
            //             var setting = {
            //                 view: {
            //                     showLine: false
            //                 },
            //                 edit: {
            //                     enable: false,
            //                     editNameSelectAll: false
            //                 },
            //                 data: {
            //                     simpleData: {
            //                         enable: true,
            //                         idKey:"orgId",
            //                         pIdKey:"orgSupId"
            //                     }
            //                 }
            //             };
            //             $.fn.zTree.init($('#orgTree'), setting, zNodes);
            //         } else {
            //             window.parent.layer.alert(data.msg);
            //         }
            //     },
            //     error: function (XMLHttpRequest, textStatus, errorThrown) {
            //         layer.alert("暂无数据，请稍后操作！" + XMLHttpRequest.status);
            //     },
            // });
        }

        // 选择器触发事件
        $(document).on("click", defProps.selectorBtn, function () {
            var input = $(this).parent().find('input'),
                type = $(this).attr('typeid');
            var layerH=publicMethods.layHeight('.listBody');
            selectorIds = !!input.attr('ids') ? input.attr('ids').split(',') : [];
            selectorNames = !!input.val() ? input.val().split(',') : [];
            if (type === '6' || type === '18') {
                // 组织
                objSelector.server = 'sysOrg/listFlatSelector';
                objSelector.where = {
                    id: 'Q_orgId_SL',
                    name: 'Q_orgName_SL'
                };
                objSelector.id = 'orgId';
                objSelector.name = 'name';
                objSelector.cols = [
                    {type: type === '6' ? 'checkbox' : 'radio'},
                    {field: 'orgId', title: 'ID', sort: true, hide: true},
                    {field: 'name', title: '组织名称', width: 160, sort: false},
                    {field: 'orgPathname', width: 230, title: '所属组织', sort: false}
                ];
            } else if (type === '8' || type === '4' || type === undefined) {  //点组件下面的选择器的时候 默认走用户单选选择器
                // 用户
                objSelector.server = 'sysUser/list';
                objSelector.where = {
                    id: 'orgId',
                    name: 'Q_fullName_SL'
                };
                objSelector.id = 'userId';
                objSelector.name = 'fullName';
                objSelector.cols = [
                    {type: type === '8' ? 'checkbox' : 'radio', fixed: 'left'},
                    {field: 'userId', title: 'ID', sort: true, hide: true},
                    {field: 'fullName', title: '姓名', sort: false,minWidth:100},
                    {field: 'orgName', title: '所属组织', sort: false,minWidth:100}
                ];
            } else if (type === '5' || type === '17') {
                // 角色
                objSelector.server = 'sysRole/list';
                objSelector.where = {
                    id: 'orgId',
                    name: 'Q_roleName_SL'
                };
                objSelector.id = 'roleId';
                objSelector.name = 'roleName';
                objSelector.cols = [
                    {type: type === '5' ? 'checkbox' : 'radio'},
                    {field: 'roleId', title: 'ID', sort: true, hide: true},
                    {field: 'roleName', title: '角色', width: 160, sort: false},
                    {field: 'systemName', width: 230, title: '子系统', sort: false}
                ];
            }
            // 选择器模板
            var listAll =$(this).attr('listAll')
            $.ajax({
                url: serverPath.qbdmsPath + setter.formLinkPath + 'extend/formDef/view/selector/selectorTme',
                // url: serverPath.qbdmsPath + setter.formLinkPath + 'formDef/view/formDesign/moulds/template/selector/selectorTme',
                type: 'GET',
                async: false,
                success: function (res) {
                    // 选择器弹窗
                    layer.open({
                        type: '1',
                        content: res,
                        title: '选择器',
                        area: ['80%', layerH],
                        btn: ['保存', '取消','撤销'],
                        skin: 'qbdms-layerFormBtn',
                        btnAlign: 'c',
                        // skin: 'form-pop-selector',
                        yes: function (index, layero) {
                            // 确定
                                 for (var i=0;i<selectorNames.length;i++){
                                     var subStr = selectorNames[i].indexOf("<");
                                     if(subStr == '-1'){
                                     }else{
                                         itemName = selectorNames[i].substr(0, subStr);
                                         selectorNames[i]=itemName;
                                     }
                                 }
                            input.val(selectorNames);
                            input.next('.getIds').val(selectorIds);
                            input.attr('ids', selectorIds);
                            layer.close(index);
                        },
                        btn3: function (index, layero) {
                            // 撤销
                            selectorIds = [];
                            selectorNames = [];
                            selectorTableInit();
                            selectorListInit();
                            return false;
                        },
                        btn2: function (index, layero) {
                            // 取消
                            selectorIds = [];
                            selectorNames = [];
                        },
                        cancel: function () {
                            // 取消
                            selectorIds = [];
                            selectorNames = [];
                        }

                    });

                    selectorTabQuery(listAll);
                }
            });

        });


        // 选择器已选择删除事件
        $(document).on("click", '.selectorTakeDel', function () {
            var ind = selectorIds.indexOf($(this).attr('trId'));
            selectorIds.splice(ind, 1);
            selectorNames.splice(ind, 1);
            selectorListInit();
            selectorTableInit();
        });


    };


    propsHandle.prototype.initSubEvent = function (defProps, serverPath, setter) {
        var temQuery = new propsHandle();

        function updateTr(copyObj, copyHtm, state) {
            // 弹窗
            layer.open({
                type: '1',
                content: '<table class="layui-form winSubCont" style="width: 480px;margin-left: 10px;padding: 0;"><tr class="temSpace" style="width: 456px;" request="template/table">' + copyHtm.html() + '</tr></table>',
                title: state === 'update' ? '修改' : '新增',
                area: '500px',
                btn: ['保存', '取消'],
                btnAlign: 'c',
                skin: 'form-sub-update',
                success: function () {
                    $('.winSubCont [type=radio]').each(function (i, item) {
                        if (state === 'update') {
                            $(item).attr('name', $(item).attr('name') + '_0');
                            item.checked = copyHtm.find('[type=radio]')[i].checked;
                        } else {
                            var len = copyObj.find('tr').length - 1;
                            $(item).attr('name', $(item).attr('name') + (len > 1 ? ('_' + len) : ''))
                        }
                    });

                    copyHtm.find('td [name]').each(function (i, item) {
                        if (item.checked) {
                            $('.winSubCont [name="' + $(item).attr('name') + '"]').attr('checked', true);
                        }
                        $('.winSubCont [name="' + $(item).attr('name') + '"]').val($(item).val());
                    });
                    form.render();
                    $('.winSubCont [isinit="1"]').each(function (i, item) {
                        $(item).attr('isinit', '2');
                    });
                    temQuery.initTemEvent(defProps, serverPath, setter);
                },
                yes: function (index) {
                    // 确定
                    if (state === 'update') {
                        copyHtm.find('[type=radio]').each(function (i, item) {
                            $('.winSubCont [type=radio]').eq(i).attr('name', $(item).attr('name'))
                        });
                        copyHtm.before($('.winSubCont').find('tr').eq(0));
                        copyHtm.remove();
                    } else {
                        copyObj.append($('.winSubCont').find('tr').eq(0));
                    }
                    var trArr = copyObj.find('tr');
                    trArr.eq(trArr.length - 1).find('td').eq(0).find('.temTag').html(trArr.length - 2);
                    layer.close(index);
                },
                cancel: function () {
                    // 取消
                }
            });
        }

        $(document).on('click', '.addFormTr', function () {

            var modetype = $(this).attr('modetype'),
                copyObj = $(this).parent().children('.subFormTable'),
                copyHtm = copyObj.find('tr').eq(1);
            if (modetype === '2') {
                //在这里做一个转换，控制子表隐藏行的必填
                var copyHtmlStr = copyHtm.html();
                copyHtmlStr = copyHtmlStr.replace(/requiredflag/g, "lay-verify");
                // 表格
                copyObj.append('<tr class="temSpace" request="template/table">' + copyHtmlStr + '</tr>');
                // copyObj.append('<tr class="temSpace" request="template/table">' + copyHtm.html() + '</tr>');
                var trArr = copyObj.find('tr');
                trArr.eq(trArr.length - 1).find('td').eq(0).find('.temTag').html(trArr.length - 2);
                trArr.eq(trArr.length - 1).find('[isinit="1"]').each(function (i, item) {
                    $(item).attr('isinit', '2');
                });
                if (trArr.length > 3) {
                    trArr.eq(trArr.length - 1).find('[type=radio]').each(function (i, item) {
                        $(item).attr('name', (trArr.eq(1).find('[type=radio]').eq(i).attr('name')) + '_' + (trArr.length - 2))
                    });
                }
                temQuery.initTemEvent(defProps, serverPath, setter);

            } else if (modetype === '1') {
                updateTr(copyObj, copyHtm);
            }

        });

        $(document).on('click', '.subUpdateTr', function () {
            var copyObj = $(this).parents('.subFormTable'),
                copyHtm = $(this).parent().parent();
            updateTr(copyObj, copyHtm, 'update')
        });


        $(document).on('click', '.subDeleteTr', function () {
            var tab = $(this).parents('.subFormTable')
            $(this).parent().parent().remove();
            tab.find('tr').each(function (i, item) {
                if (i > 0) {
                    $(item).find('td').eq(0).find('.temTag').html(i - 1);
                }
                if (i > 1) {
                    $(item).find('[type=radio]').each(function (j, itemj) {
                        var nameL = tab.find('tr').eq(1).find('[type=radio]').eq(j).attr('name')
                        $(itemj).attr('name', nameL + (i > 2 ? ('_' + (i - 1)) : ''))
                    })
                }

            })
            publicMethods.bottomFixd()
        });

        //子表行上移
        $(document).on('click', '.subUpTr', function () {
            var tr = $(this).parent().parent();
            var cla = tr.prev().attr("class");
            if(cla==="temSpace subContTem"){
                return false;
            }
            $(tr).insertBefore($(tr).prev());
            var tab = $(this).parents('.subFormTable');
            tab.find('tr').each(function (i, item) {
                if (i > 0) {
                    $(item).find('td').eq(0).find('.temTag').html(i - 1);
                }
                if (i > 1) {
                    $(item).find('[type=radio]').each(function (j, itemj) {
                        var nameL = tab.find('tr').eq(1).find('[type=radio]').eq(j).attr('name');
                        $(itemj).attr('name', nameL + (i > 2 ? ('_' + (i - 1)) : ''))
                    })
                }

            })
        });
        //子表行下移
        $(document).on('click', '.subDownTr', function () {
            var tr = $(this).parent().parent();
            $(tr).insertAfter($(tr).next());
            var tab = $(this).parents('.subFormTable');
            tab.find('tr').each(function (i, item) {
                if (i > 0) {
                    $(item).find('td').eq(0).find('.temTag').html(i - 1);
                }
                if (i > 1) {
                    $(item).find('[type=radio]').each(function (j, itemj) {
                        var nameL = tab.find('tr').eq(1).find('[type=radio]').eq(j).attr('name');
                        $(itemj).attr('name', nameL + (i > 2 ? ('_' + (i - 1)) : ''))
                    })
                }

            })
        });

        //按钮-自定义对话框设置解析
        $(document).on('click','.temButton',function () {
            var dialogInstallData = JSON.parse($(this).attr('dialoginstall'));
            //条件字段
            var conditionStr = "";
            for(var i=0;i<dialogInstallData.conditionField.length;i++){
                var conditionField = dialogInstallData.conditionField[i];
                conditionStr += conditionField.field;
                conditionStr += "=";
                var inputValue = conditionField.initValue;
                var formFieldValue = $("input[name='m:"+dialogInstallData.tableName+":"+conditionField.selectField+"']").val();
                if(formFieldValue){
                    inputValue = formFieldValue;
                }
                conditionStr += inputValue;
                if(i < dialogInstallData.conditionField.length-1) {
                    conditionStr += "&";
                }
            }

            //返回字段解析
            var  parseReturnData=function(returnData,selectDataIds) {
                var fieldNames = [];
                var childNodes = [];
                for(var i=0;i<dialogInstallData.zTreeNodes.length;i++){
                    if(dialogInstallData.zTreeNodes[i].children.length>0) {
                        var nodeName = dialogInstallData.zTreeNodes[i].fieldName;
                        fieldNames.push(nodeName.substr(0, nodeName.length - 4));
                        childNodes.push(dialogInstallData.zTreeNodes[i].children);
                    }
                }
                var rtnData = JSON.parse(returnData);
                //返回值类型为数组,先将数组转化为对象，重复字段的字符串拼接到一起
                if(rtnData instanceof Array){
                    var rtnObj = {};
                    rtnData.forEach(function (rtnEveryData) {
                        var fieName = [];
                        for(var p in rtnEveryData){
                            fieName.push(p);
                        }
                        fieName.forEach(function (rtnEveryKey) {
                            if(rtnEveryKey in rtnObj){
                                rtnObj[rtnEveryKey] += (","+rtnEveryData[rtnEveryKey]);
                            }else {
                                rtnObj[rtnEveryKey] = rtnEveryData[rtnEveryKey];
                            }
                        });
                    });
                    rtnData = rtnObj;
                }
                for(var i=0;i<fieldNames.length;i++){
                    //判断对象中是否存在某属性
                    if(fieldNames[i] in rtnData){
                        var fieldValue = rtnData[fieldNames[i]];
                        for(var j=0;j<childNodes[i].length;j++){
                            var formInputName = 'm:'+dialogInstallData.tableName+':'+childNodes[i][j].fieldName;
                            $("input[name='"+formInputName+"']").val(fieldValue);
                            $("select[name='"+formInputName+"']").val(fieldValue);
                            if(j==0){
                               $("input[name='"+formInputName+"']").before("<input type='hidden' name='selectIds'>");
                                $("input[name=selectIds]").val(selectDataIds);
                            }
                        }
                    }
                }
                form.render();
            };

            //根据自定义对话框与组合对话框的不同，走不同的ajax
            if(dialogInstallData.selectDialogAlias[0] === 'd'){
                var dialogAlias = dialogInstallData.selectDialogAlias.substr(7);
                CommonDialog(dialogAlias, function (dialogReturnData,selectDataIds) {
                    parseReturnData(dialogReturnData,selectDataIds);
                },conditionStr);
            }else{
                var combinationAlias = dialogInstallData.selectDialogAlias.substr(12);
                CommonCombinationDialog(combinationAlias,function (combinationReturnData,selectDataIds) {
                    parseReturnData(combinationReturnData,selectDataIds);
                },conditionStr);
            }

        });

    };

    propsHandle.prototype.initTemEvent = function (defProps, serverPath, setter) {
        //--- 日期----
        $(defProps.temDate).each(function (i, item) {
            $(item).removeAttr("eventHandler");
            laydate.render({
                elem: item, //指定元素
                format: $(item).attr('format') || 'yyyy-MM-dd HH:mm:ss',
                type: $(item).attr('datetype') || 'datetime',
                value: $(item).attr('displaydate') === '1' ? new Date() : '',
                done: function () {
                    $(item).change();
                }
            });
            $(item).click(function () {
                return false;
            });
        });

        // 下拉框

        $(defProps.selectInput).each(function () {
            $(this).mouseup(function () {
                return false;
            })
        });

        // ---文件上传---


        $(defProps.formAreaInfo + ' ' + defProps.uploadFileBtn).each(function (i, item) {
            if ($(item).attr('isInit') !== '1') {
                var exts = $(item).attr('fileTypes') ? $(item).attr('fileTypes').split(';').join('|').split('.').join('') : '';
                upload.render({
                    elem: item,
                    url: serverPath.qbdmsPath + setter.sysLinkPath + 'attachFile/fileUpload',
                    multiple: true,
                    accept: 'file',
                    auto: true,
                    exts: exts,
                    //附件密级的值传到后台接口
                    before: function (obj) {
                       this.data = {"fileLevel": $(item).next().next().children("select").val()};
                    },
                    progress: function (e, percent) {
                        // console.log(percent)
                    },
                    done: function (res, index, upload) {
                        if (res.code === 0 && res.data && res.data.fileList.length > 0) {
                            var fileOne = res.data.fileList[0],
                                str = '<li fileId=' + fileOne.fileId + '><p onclick="downFile(this)">' + fileOne.fileName + '.' + fileOne.extName + '</p><i class="layui-icon layui-icon-delete deleteFile" ></i></li>';
                            $(item).parents('.uploadFileCont').find('.uploadFileList').append(str);
                        }
                    },
                    error: function (index) {
                        // console.log(index)
                    }
                });

                $(item).attr('isInit', '1')
            }
        });

        //  图片上传

        $(defProps.formAreaInfo + ' ' + defProps.uploadImgBtn).each(function (i, item) {
            if ($(item).attr('isInit') !== '1') {

                upload.render({
                    elem: item,
                    url: serverPath.qbdmsPath + setter.sysLinkPath + 'attachFile/fileUpload',
                    multiple: true,
                    accept: 'image',
                    auto: true,
                    progress: function (e, percent) {
                    },
                    done: function (res, index, upload) {

                        if (res.code === 0 && res.data && res.data.fileList.length > 0) {
                            var fileOne = res.data.fileList[0],
                                fileId = fileOne.fileId,
                                str = '<li fileId=' + fileId + '><div class="fileByImg"><img onclick="downFile(this)" src="' + serverPath.qbdmsPath + setter.sysLinkPath + 'attachFile/getFileById?fileId=' + fileId + '" /></div><i class="layui-icon layui-icon-delete deleteFile" ></i></li>'

                            $(item).parents('.uploadImgCont').find('.uploadImgList').html(str);
                        }
                    },
                    error: function (index) {
                        // console.log(index)
                    }
                });

                $(item).attr('isInit', '1')
            }
        });


        // 富文本

        $(defProps.richTextArea).each(function (i, item) {
            var height = $(item).parent().find('.layui-layedit .layui-layedit-iframe > iframe').height();
            layedit.build(item, {
                height: height || 100,
                uploadImage:{
                    url: serverPath.qbdmsPath + setter.sysLinkPath +'attachFile/uploadImage',
                    type:"post"
                }
            });
        });

        // 数据词典
        $(defProps.formAreaInfo + ' ' + defProps.dataLexiTree).each(function (i, item) {
            if ($(item).attr('isInit') !== '1') {
                function initTree(nodes) {
                    $(item).html('');
                    tree.render({
                        elem: item,
                        data: nodes,
                        click: function (node) {
                            var $select = $($(this)[0].elem).parents(".layui-form-select");
                            $select.removeClass("layui-form-selected").find(".layui-select-title span").html(node.data.title).end().find("input.dataLexiVal").val(node.data.id);
                            return false;
                        }
                    });
                }
                $.ajax({
                    url: serverPath.qbdmsPath + setter.sysLinkPath + 'dictionary/treeList',
                    type: "GET",
                    data: {
                        nodeKey: $(item).attr('dicttype')
                    },
                    dataType: 'json',
                    async: false,
                    success: function (result) {
                        var list = result.data.dicList
                        var type = result.data.type

                        var panel = $(item).parents('.dataLexiPanel')
                        panel.find('.dataLexiVal').attr("dicType",type);
                        if (type === 0) {
                            panel.find('.lexiTree').hide();
                            panel.find('.lexiSelect').show();
                            panel.find('.lexiSelectCont').html('<option value="">请选择</option>');
                            for (var i = 0; i < list.length; i++) {
                                panel.find('.lexiSelectCont').append('<option value=' + list[i].itemValue + '>' + list[i].itemName + '</option>');
                            }
                            form.render();
                        } else {
                            panel.find('.lexiTree').show();
                            panel.find('.lexiSelect').hide();
                            initTree(list)
                        }
                    }
                });


                $(item).attr('isInit', '1')
            }
        });
        form.render();


    };


    exports('propsHandle', propsHandle);
});

//附件下载功能
function downFile(obj){
    var fileId =  $(obj).parents("li").attr("fileid");
    window.location.href = serverPath.qbdmsPath + setter.sysLinkPath + "attachFile/download?fileId="+fileId;
}